package ru.ifmo.croak.impl.stress.post.team3;

import java.util.ArrayList;
import java.util.Vector;

import ru.ifmo.croak.api.PostService;

/**
 * @author Artem Bochkarev
 * 
 */
public class Tester implements Runnable {

	private final int numProcesses;
	private final int delay;
	private final PostService postService;
	private volatile Vector<Thread> threads;
	private volatile boolean stopped = false;

	public Tester(int numOfProcesses, int delay, PostService postService) {
		numProcesses = numOfProcesses;
		this.delay = delay;
		this.postService = postService;
	}

	public void stop() {
		for (Thread thread : threads) {
			thread.interrupt();
		}
		stopped = true;
	}

	@Override
	public void run() {
		ArrayList<SimpleSender> senders = new ArrayList<SimpleSender>(numProcesses);
		for (int i = 0; i < numProcesses; ++i) {
			senders.add(new SimpleSender(delay, postService));
		}
		threads = new Vector<Thread>(numProcesses);
		try {
			for (SimpleSender sender : senders) {
				threads.add(new Thread(sender));
			}
			for (Thread thread : threads) {
				thread.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		while (!stopped) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
		stop();
	}
}